/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.dao;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.chacha.exception.ChachaRuntimeException;
import org.chacha.log.LogPrn;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;

/**
 * 
 *	@author: hejing
 *	@date: 2012-11-7-下午01:56:38
 */
public class MongoConnection implements Connection{
	private LogPrn log=new LogPrn(MongoConnection.class);
    private DB db;

    private String connectionHost;				//db的ip
    private Integer connectionPort;				//db的端口
    private String connectionDatabase;			//db名称
    private String connectionDescriptor;		//连接串，适用于多db server的情况，连接描述符配置了，则dbServerIP、dbServerPort配置失效.格式ip1:port1,ip2:port2
    private int connectionsPerHost=90;			//连接池大小
    private int threadsAllowedToBlockForConnectionMultiplier=20; //等待连接的线程乘数,与连接池大小相乘，为允许等待的线程数
    private int connectTimeout=30000;			//建立数据库连接时的超时时长，单位毫秒
    private boolean autoConnectRetry=true;		//是否自动重连
    
    public MongoConnection() {
		super();
	}

	public void setConnectionDatabase(String connectionDatabase) {
        this.connectionDatabase = connectionDatabase;
    }

    public void setConnectionPort(Integer connectionPort) {
        this.connectionPort = connectionPort;
    }

    public void setConnectionHost(String connectionHost) {
        this.connectionHost = connectionHost;
    }

    public String getConnectionDescriptor() {
        return connectionDescriptor;
    }

    public void setConnectionDescriptor(String connectionDescriptor) {
        this.connectionDescriptor = connectionDescriptor;
    }
    
    public void setConnectionsPerHost(int connectionsPerHost) {
		this.connectionsPerHost = connectionsPerHost;
	}

	public void setThreadsAllowedToBlockForConnectionMultiplier(
			int threadsAllowedToBlockForConnectionMultiplier) {
		this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}

	public void setAutoConnectRetry(boolean autoConnectRetry) {
		this.autoConnectRetry = autoConnectRetry;
	}

	@Override
    public void connect() {
        try {
            Mongo mongo;
            if (connectionDescriptor != null) {
                String[] hosts = connectionDescriptor.split(",");
                List<ServerAddress> addr = new ArrayList<ServerAddress>();
                for (String host: hosts) {
                    String[] hostPortPair = host.split(":");
                    int port = 27017;
                    if (hostPortPair.length > 1) {
                        try {
                            port = Integer.parseInt(hostPortPair[1]);
                        } catch (NumberFormatException e) {
                            
                        }
                    }
                    addr.add(new ServerAddress(hostPortPair[0], port));
                }
                mongo = new Mongo(addr);
            } else {
                mongo = new Mongo(connectionHost, connectionPort);
            }
            //连接池参数
            MongoOptions opt = mongo.getMongoOptions();
            opt.setConnectionsPerHost(connectionsPerHost);
            opt.setThreadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
            opt.setAutoConnectRetry(autoConnectRetry);
            opt.setConnectTimeout(connectTimeout);
            db = mongo.getDB(connectionDatabase);
            log.info("MongoConnection init success!");
        } catch (UnknownHostException e) {
            throw new ChachaRuntimeException(e);
        }
    }
    @Override
    public DBCollection getCollection(String name) {
        return db.getCollection(name);
    }

    public void dropDatabase() {
        db.dropDatabase();
    }

}
